package com.lhz.collector.source;

import com.lhz.collector.common.Constant;
import org.apache.flume.ChannelException;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.EventDrivenSource;
import org.apache.flume.conf.Configurable;
import org.apache.flume.conf.Configurables;
import org.apache.flume.instrumentation.SourceCounter;
import org.apache.flume.source.AbstractSource;
import org.jboss.netty.bootstrap.ConnectionlessBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.oio.OioDatagramChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketOptions;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class NettyUDPSource extends AbstractSource
                             implements EventDrivenSource, Configurable {

  private int port;
  private int maxsize = 1 << 16; // 64k is max allowable in RFC 5426
  private String host = null;
  private Channel nettyChannel;
  private AtomicInteger count=new AtomicInteger(0);

  private static final Logger logger = LoggerFactory.getLogger(NettyUDPSource.class);

  private SourceCounter sourceCounter;

  // Default Min size
  public static final int DEFAULT_MIN_SIZE = 2048;
  public static final int DEFAULT_INITIAL_SIZE = DEFAULT_MIN_SIZE;

  public class syslogHandler extends SimpleChannelHandler {
    private NettyUtils syslogUtils = new NettyUtils(DEFAULT_INITIAL_SIZE,true);

    public void setEventSize(int eventSize) {
      syslogUtils.setEventSize(eventSize);
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent mEvent) {
      try {
        Event e = syslogUtils.extractEvent((ChannelBuffer)mEvent.getMessage());
        if (e == null) {
          return;
        }
        System.out.println(new String(e.getBody()));
        System.out.println(count.incrementAndGet());
        sourceCounter.incrementEventReceivedCount();
        //记录来源IP
        String IP=((InetSocketAddress)mEvent.getRemoteAddress()).getAddress().getHostAddress();
        e.getHeaders().put(Constant.IP,IP);
        getChannelProcessor().processEvent(e);
        sourceCounter.incrementEventAcceptedCount();
      } catch (ChannelException ex) {
        logger.error("Error writting to channel", ex);
        return;
      } catch (RuntimeException ex) {
        logger.error("Error parsing event from syslog stream, event dropped", ex);
        return;
      }
    }
  }

  @Override
  public void start() {
    // setup Netty server
    ConnectionlessBootstrap serverBootstrap = new ConnectionlessBootstrap(
        new OioDatagramChannelFactory(Executors.newCachedThreadPool()));
    final syslogHandler handler = new syslogHandler();
    handler.setEventSize(maxsize);
    Integer receiveBufferSize=new Integer(maxsize*1024);//设置缓冲区的大小为64M，尽量保证不丢数据
    serverBootstrap.setOption("receiveBufferSize",receiveBufferSize);
    serverBootstrap.setOption("receiveBufferSizePredictorFactory",
        new AdaptiveReceiveBufferSizePredictorFactory(DEFAULT_MIN_SIZE,
            DEFAULT_INITIAL_SIZE, maxsize));
    serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
      @Override
      public ChannelPipeline getPipeline() {
        return Channels.pipeline(handler);
      }
    });

    if (host == null) {
      nettyChannel = serverBootstrap.bind(new InetSocketAddress(port));
    } else {
      nettyChannel = serverBootstrap.bind(new InetSocketAddress(host, port));
    }

    sourceCounter.start();
    super.start();
  }

  @Override
  public void stop() {
    logger.info("Syslog UDP Source stopping...");
    logger.info("Metrics: {}", sourceCounter);
    if (nettyChannel != null) {
      nettyChannel.close();
      try {
        nettyChannel.getCloseFuture().await(60, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
        logger.warn("netty server stop interrupted", e);
      } finally {
        nettyChannel = null;
      }
    }

    sourceCounter.stop();
    super.stop();
  }

  @Override
  public void configure(Context context) {
    Configurables.ensureRequiredNonNull(
        context, "port");
    port = context.getInteger("port");
    host = context.getString("host");
    if (sourceCounter == null) {
      sourceCounter = new SourceCounter(getName());
    }
  }
}
